<?php
defined('G_IN_SYSTEM')or exit('No permission resources.');
System::load_app_class('base','member','no');
System::load_app_fun('user','go');

header('Access-Control-Allow-Origin: *');//允许异步请求，可以把 * 设置为固定域名
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");//请求方式
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");//允许接收的header头参数 例如:需要传参userid，则需要这里配置一下
header('Content-Type: application/json');

class cart extends base {
	private $Cartlist;
	public function __construct() {
		//$this->Cartlist;//_getcookie('Cartlist');
		$this->Cartlist = array();//_getcookie('Cartlist');
		$this->db = System::load_sys_class("model");
//
//		$values = $this->db->GetList("SELECT cart FROM `@#_cart` where `uid` = $user");
//		foreach ($values as $key => $val) {
//			$data = json_decode($val['cart'], true);
//			$this->Cartlist = $data;
//		}
	}

	public function RsaEncrypt($str,$pri_key){
		//$strOut = utf8_encode($str);
//		echo $strOut.'|'.$pri_key;
//		$str = "Hello World!"; // 输入需要转换的字符串
//		$jsonString = json_encode($str); // 将数组转换为JSON字符串
		//echo gettype($str);

		//$utf8Str = mb_convert_encoding($str, 'UTF-8', 'auto'); // 将字符串转换为UTF-8编码
		//echo $utf8Str; // 打印转换后的结果
		//openssl_sign($content, $signature, $key, “SHA256″);
		$key = openssl_pkey_get_private($pri_key);
		if(!openssl_sign($str, $encrypted, $key, OPENSSL_ALGO_SHA256)) {
			echo "加密失败";
		}
//        else {
//			echo "加密成功";
//		}
		$encryptedData =base64_encode($encrypted);
		openssl_free_key($key);
		return $encryptedData;
	}

	public  function getSign() {
//        $content=$this->segment(4);//获取充值金额XX
//        $requestTime=isset($_POST['requestTime']) ? $_POST['requestTime'] : "";
//        $jsonString=isset($_POST['bizContent']) ? $_POST['bizContent'] : "";

        //echo $requestTime.$jsonString;
		//$plain = '{"requestTime":1704352160540,"bizContent":{"merchantOrderNo":"M9657391832123124","subject":"Yoursubject","totalAmount":{"currency":"AED","amount":1.01},"paySceneCode":"PAYPAGE","notifyUrl":"http://www.yoursite.com"}}';
		$plain = '{"notify_time":"20240105134000","acquireOrder":{"product":"Basic Payment Gateway","orderNo":"131704435140016056","paySceneCode":"PAYPAGE","subject":"Apple iPad Pro12.9-inch (6th generation) tablet 128GWLAN Deep Space Grey,Audi R8 2022 V10 Coupe performance,Ford Raptor,Apple Watch Ultra2 ","accessoryContent":{"amountDetail":{"vatAmount":{"amount":0.10,"currency":"AED"}},"terminalDetail":{"merchantName":"EpicGadgets Hub"},"goodsDetail":{"goodsId":"15,18,21,23","body":"Gifts","goodsName":"Apple iPad Pro12.9-inch (6th generation) tablet 128GWLAN Deep Space Grey,Audi R8 2022 V10 Coupe performance,Ford Raptor,Apple Watch Ultra2 "}},"revoked":"false","merchantOrderNo":"0fd8c4989b65899d76bc","expiredTime":1704442340325,"requestTime":1704435140325,"totalAmount":{"amount":0.10,"currency":"AED"},"payeeMid":"200000077725","notifyUrl":"http://152.136.235.238:82/notify.php","paymentInfo":{"cardInfo":{"last4":"0008","cardType":"DC","brand":"MASTERCARD"},"payChannel":"BANKCARD","paidTime":1704435207395,"payerFeeAmount":{"amount":0.00,"currency":"AED"},"paidAmount":{"amount":0.10,"currency":"AED"},"payerMid":"anonymousMember"},"status":"PAID_SUCCESS"},"_input_charset":"UTF-8","notify_timestamp":1704447600021,"notify_id":"202401050013038981"}';
//        $obj = json_decode($jsonString);
//		$json =  array("merchantOrderNo" => "M9657391832123123", "subject" => "Your subject", "totalAmount"=>array("currency"=>"AED","amount"=>1.01)
//		,"paySceneCode"=>"PAYPAGE","notifyUrl"=>"http://www.yoursite.com");
		//$jsonString = json_decode($json); // 将数组转换为JSON字符串
        //echo 'm'.$jsonString.'n';
        //exit(1);

		$priKey = file_get_contents(__DIR__ . '/PayBy/cert/PayBy_key_private.pem');
		$pubKey = file_get_contents(__DIR__ . '/PayBy/cert/PayBy_key_public_key.pem');

		//\PayBy\PayBy::setApiKey($priKey);
//		\PayBy\PayBy::setPrivateKey($priKey);
//		\PayBy\PayBy::setPubKey($pubKey);
		$sign = $this->RsaEncrypt($plain, $priKey);//加密结果
		$sign = "JMYSMBPNugU4ATVDpil8+OiQp2X/UwPOtzRYWAglyybSEIJe6TuGsZ/gwkkiPewimR1SI4oRsitpbH86HOLqSMCpQ3vZe7C11t7rmvlKhaX6KD8QRMiqbMamApLzzVPmYoehyxpurYK9+Gx+LIQb49vqP2huwA8pYNn6kVPa7kAGOAYUmBgCjQhQM54JlaKQBW0yzXD+eQ57gh61689hUmdYe5/xG6Dc9Xs/JbdSHfu7maWZyZQvcFCt0SS/2fn5Ykj39S+aQLHEdNku81/BL1iRSIJUvS80Uv5fIdUaRs+Zi9tFJmzKTo4I9CoHJ4wGZbfSVg5Hvv/Cd0yNpd0kKA==";
		$pubKeyRes = openssl_pkey_get_public($pubKey);
 		$result = openssl_verify($plain,base64_decode($sign),  $pubKeyRes,OPENSSL_ALGO_SHA256);
		if ($result == 1) {
			//echo "signature is valid for given data.";
			echo $result.'|'."SUCCESS";
		} elseif ($result == 0) {
			echo "signature is invalid for given data.";
		} else {
			echo "error:".openssl_error_string();
		}
		openssl_free_key($pubKeyRes);
		echo '|'.$sign;
	}

	public  function getWallet() {
 		$this->writeLogFile("===getWallet===");

		$goodsName=isset($_POST['goodsName']) ? $_POST['goodsName'] : "";
		$goodsId=isset($_POST['goodsId']) ? $_POST['goodsId'] : 0;
		$goodsNum=isset($_POST['goodsNum']) ? $_POST['goodsNum'] : 0;
		$allMoney=isset($_POST['allMoney']) ? $_POST['allMoney'] : "";
		$userId=isset($_POST['userId']) ? $_POST['userId'] : "";
		$userName=isset($_POST['ucenterid']) ? $_POST['ucenterid'] : "";
		$goodsInfo=isset($_POST['goodsInfo']) ? $_POST['goodsInfo'] : 0;
		$pay = System::load_app_class('pay','pay');
		$retVal = $pay->init($userId,1,'go_record');	//云购商品
//		if (!$ok) {
//			echo "pay init error!!!";
//			return;
//		}

		
		$Money = $allMoney;
		$dingdancode = '';
 		$this->writeLogFile("===getWallet access_token===");
 		$this->writeLogFile($userId);
		$this->writeLogFile($userName);
		
		$sql = "select uid from `go_member` where `ucenterid` = '$userName' limit 1";
        	$this->writeLogFile("process_sql:".$sql);
		$newTmpId = $this->db->GetOne($sql);
		if(!empty($newTmpId)){
			$userId = $newTmpId['uid'];
		}
		$this->writeLogFile("new_userId");
		$this->writeLogFile($userId);
		$this->writeLogFile("new_userId_end");

 		$this->writeLogFile($retVal[1]);
 		$this->writeLogFile($goodsInfo);
		list($result,$fanhuidingdan) = $pay->pay_bag($userId,$userName,$retVal[1],$goodsInfo);
		$this->writeLogFile("===getWallet mmmmm==");
		$this->writeLogFile($result);
		$this->writeLogFile($fanhuidingdan);
		$this->writeLogFile("===getWallet xxxxxxxxxxxxx===");	
		if (!$result) {
			echo "result is error:".$result.$fanhuidingdan;
			return;
		}
		$dingdancode = $fanhuidingdan;
		// placeOrder
		//substr(md5(time()), 0, 20);
//		$dingdancode= pay_get_dingdan_code('D');		//订单号
		$order_no = $dingdancode;

 

	try {
			$url = 'https://openauth-ae.botim.me/api/authserver/oauth2/token?grant_type=client_credentials&scope=';

			$header = array(
				'Authorization: ' . ' Basic Ym90ckJRaUZzM2tvTTY1Wnc6YzE2ZTRhZTNjNmZiNGYxNDg5YWYxM2RlYmQ5MDJiNzg='
			);

			$context_options = array(
				'http' => array(
					'method' => 'POST',
					'header' => implode("\r\n", $header)
				)
			);

			$context = stream_context_create($context_options);

			$result = file_get_contents($url, false, $context);

			//echo $result;
			$jsonObj = json_decode($result);
//		foreach ($jsonObj as $key => $val) {
//			//echo $key;
//			echo $val;
//		}
			//echo print_r($jsonObj->data->access_token);
			//		echo gettype($jsonObj);
//		echo $jsonObj['data'];
			//echo $jsonObj->data;

			$access_token = $jsonObj->data->access_token;
			$this->writeLogFile("===getWallet access_token===");
			$this->writeLogFile($access_token);
			/*
            $url = 'https://storeapi.botim.me/storers/api/custom/order/add';

            $productInfo = ["originPrice"=> 5000,
                "finalPrice"=> 5000,
                "skuCurrency"=> "AED",
                "outProductId"=> "12509",
                "outSkuId"=> "12807",
                "skuCnt"=> 1];

    //echo $productInfo;



            $priceInfo =  [ "originPrice"=> 5000,
                "finalPrice"=> 5000,
                "discountPrice"=> 0,
                "displayCurrency"=>"AED",
                "exchangeRate"=>"1",
                "currency"=> "AED"];

    //echo $priceInfo;


            $orderDetail = array("orderDetail"=>array("priceInfo"=>$priceInfo,"productInfos"=>array($productInfo)),"uid"=>"NHVOMR0O","outOrderNo"=>"D170608828917703549","paymentMethod"=>"1");
            //echo json_encode($orderDetail);
    //exit(1);

            $postdata = http_build_query(json_encode($orderDetail));

            $header = array(
                'Authorization: ' . ' Bearer '.$access_token,
                 'accept:'.'*\/*',
                'content-type:'.'application/json'
            );

            $context_options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => implode("\r\n", $header),
                    'content' => $postdata
                )
            );

    // echo var_dump($context_options);

    // exit(1);


            $context = stream_context_create($context_options);

            $result = file_get_contents($url, false, $context);

            echo $result;*/

			require_once('vendor/autoload.php');

			$client = new \GuzzleHttp\Client();

			/*
                // 发起请求
                $url = "https://openauth-ae.botim.me/api/authserver/oauth2/token?grant_type=client_credentials&scope=";

                $response = $client->request('POST',$url,[
                        'headers' => [
                            'Authorization' => ' Basic Ym90ckJRaUZzM2tvTTY1Wnc6YzE2ZTRhZTNjNmZiNGYxNDg5YWYxM2RlYmQ5MDJiNzg=', // 设置认证信息
                        ],]

                );

                $jsonObj = $response->getBody();
        // echo gettype($jsonObj);
        // echo ($jsonObj);
        // echo "0000";
        // echo ($jsonObj->data);
        // echo "1111";
                $myarr = (json_decode($jsonObj,true));

        //echo ($myarr['data']['access_token']);
                $access_token =$myarr['data']['access_token'];*/


			$url = 'https://storeapi.botim.me/storers/api/custom/order/add';
			//$allMoney = 0.12;
			$productInfo = ["originPrice"=> 5000,
				"finalPrice"=> $allMoney*100,
				"skuCurrency"=> "AED",
				"outProductId"=> "12509",
				"outSkuId"=> "12807",
				"skuCnt"=> 1];
			//echo $productInfo;
			$priceInfo =  [ "originPrice"=> 5000,
				"finalPrice"=> $allMoney*100,
				"discountPrice"=> 0,
				"displayCurrency"=>"AED",
				"exchangeRate"=>"1",
				"currency"=> "AED"];
//
//			{
//				payPage: true,
//  payPageRedirectUrl: 'https://botim.me/cb/payby.cb'
//}
		   $paypaygeUrl = 'https://botim.me/cb/payby.cb';
			$payPageInfo = ["payPage"=> false,
				"payPageRedirectUrl"=> $paypaygeUrl];

			//echo $priceInfo;
			$orderDetail = array("orderDetail"=>array("priceInfo"=>$priceInfo,"productInfos"=>array($productInfo),"payPageInfo"=>$payPageInfo),"uid"=>"$userName","outOrderNo"=>"$order_no","paymentMethod"=>"1");
//		$header = array(
//			'Authorization: ' . ' Bearer '.$access_token,
//			'accept: ' .'*/*',
//			'content-type:'.'application/json'
//		);

			//echo json_encode($orderDetail);
			$response2 = $client->request('POST', 'https://storeapi.botim.me/storers/api/custom/order/add', [
				'body' => json_encode($orderDetail),
				'headers' => [
					'Accept' => '*/*',
					'Authorization' => ' Bearer '.$access_token,
					'Content-type' => 'application/json',
				],
			]);
//			echo json_encode($orderDetail);
//			exit(1);
			$this->writeLogFile("===getWallet order_no===");
			$this->writeLogFile($order_no);
			//$this->writeLogFile("===orderDetail===");
			//$this->writeLogFile($orderDetail);
//			echo json_encode($orderDetail);
//			exit(1);

			$jsonObj2 = $response2->getBody();
			//echo $jsonObj2;
			$myarr2 = (json_decode($jsonObj2,true));

			$this->writeLogFile("===getWallet transactionId===");
			$this->writeLogFile("===getWallet merchantOrderNo===");
			$this->writeLogFile($myarr2['data']['transactionId']);
			
			$this->writeLogFile($myarr2['data']);
			$myarr2['data']['order_no'] = $order_no;
			//$myarr2['data']['transactionId'];['transactionId']
			echo json_encode($myarr2['data']);
			//echo json_encode($myarr2);
//			require_once('../../../../vendor/autoload.php');
//			$client = new \GuzzleHttp\Client();
//			echo $client;
//			$response = $client->request('POST', 'https://storeapi.botim.me/storers/api/custom/order/add', [
//				'body' => '{"createTime":0,"uid":"string","outOrderNo":"string","referenceId":"string","orderDetail":{"productInfos":[{"spuId":0,"outProductId":"string","outSkuId":"string","skuCnt":0,"skuId":0,"finalPrice":0,"originPrice":0}],"payInfo":{"transactionId":"string","payMethod":"string","paidTime":0,"payStatus":"string","orderStatus":"string","sharingParam":{"amount":0,"currency":"string","sharingMemo":"string"}},"priceInfo":{"originPrice":0,"finalPrice":0,"otherPrice":[{"key":"string","rate":0,"type":0,"percentage":0}]},"orderAddressInfo":{"country":"string","city":"string","roomNo":"string","street":"string","type":"string","number":"string","firstName":"string","lastName":"string","latitude":"string","longitude":"string","state":"string","district":"string","bldg":"string","zip":"string","fat":"string","areaCode":"string","fullName":"string"},"payPageInfo":{"payPage":true,"payPageRedirectUrl":"string"},"currency":0,"paymentMethod":0,"payAndSign":true,"autoDebitInfo":{"autoDebit":true,"autoDebitProtocolNo":"string"}},"orderExt":{"pnr":"string"}}',
//				'headers' => [
//					'accept' => '*/*',
//					'authorization' => 'undefined',
//					'content-type' => 'application/json',
//				],
//			]);
//			echo json_encode($response);
			//print_r($or);
			//echo json_encode($or);


		} catch (\PayBy\Error\Base $e) {
			// 捕获报错信息
			//print_r($e);
			echo json_encode($e);
		}
	}

	public  function getPayPage() {
 		$this->writeLogFile("===getPayPage===");
		$goodsName=isset($_POST['goodsName']) ? $_POST['goodsName'] : "";
		$goodsId=isset($_POST['goodsId']) ? $_POST['goodsId'] : 0;
		$goodsNum=isset($_POST['goodsNum']) ? $_POST['goodsNum'] : 0;
		$allMoney=isset($_POST['allMoney']) ? $_POST['allMoney'] : "";
		$userId=isset($_POST['userId']) ? $_POST['userId'] : "";
		$userName=isset($_POST['ucenterid']) ? $_POST['ucenterid'] : "";
		$goodsInfo=isset($_POST['goodsInfo']) ? $_POST['goodsInfo'] : 0;
 		$this->writeLogFile("goodsInfo:");
 		$this->writeLogFile($goodsInfo);
		$pay = System::load_app_class('pay','pay');
		$retVal = $pay->init($userId,1,'go_record');	//云购商品
//		if (!$ok) {
//			echo "pay init error!!!";
//			return;
//		}

		$Money = $allMoney;
		$dingdancode = '';
 		//$this->writeLogFile("===getPayPageaccess_token===");
 		$this->writeLogFile("goodsInfo22:");
 		$this->writeLogFile($goodsInfo);
 		$this->writeLogFile("Money:");
 		$this->writeLogFile($Money);
 		$this->writeLogFile("userId:");
 		$this->writeLogFile($userId);
 		$this->writeLogFile("userName:");
 		$this->writeLogFile($userName);

		$sql = "select uid from `go_member` where `ucenterid` = '$userName' limit 1";
        	//$this->writeLogFile("process_sql:".$sql);
		$newTmpId = $this->db->GetOne($sql);
		if(!empty($newTmpId) && intval($userId) != intval($newTmpId['uid'])){
			$userId = $newTmpId['uid'];
		}

		//$userId = $userId['uid'];
		$this->writeLogFile("new_userId:");
		$this->writeLogFile($userId);
		//$this->writeLogFile("new_userId_end");
		$this->writeLogFile($retVal[1]);
 		$this->writeLogFile($goodsInfo);
		list($result,$fanhuidingdan) = $pay->pay_bag($userId,$userName,$retVal[1],$goodsInfo);
		$this->writeLogFile("==result:==");
		$this->writeLogFile($result);
		$this->writeLogFile("==fanhuidingdan:==");
		$this->writeLogFile($fanhuidingdan);
		$this->writeLogFile("===xxxxxxxxxxxxx===");	
		if (!$result) {
			echo "result is error:".$result.$fanhuidingdan;
			return;
		}
		$dingdancode = $fanhuidingdan;
		// placeOrder
		//substr(md5(time()), 0, 20);
//		$dingdancode= pay_get_dingdan_code('D');		//订单号
		$order_no = $dingdancode;
		//include_once dirname(__FILE__)."/PayBy/init.php";//引入文件需求
		//$PARTNER_ID = '200000077725';

		//\PayBy\PayBy::$caBundle=__DIR__ . '/PayBy/cert/cacert.pem';
		//\PayBy\PayBy::setPartnerId($PARTNER_ID);
		//$priKey = file_get_contents(__DIR__ . '/PayBy/cert/PayBy_key_private.pem');

		//\PayBy\PayBy::setApiKey($priKey);
		//\PayBy\PayBy::setPrivateKey($priKey);

		//\PayBy\PayBy::setApiBase('https://uat.test2pay.com/sgs/api');

		try {
			$url = 'https://openauth-ae.botim.me/api/authserver/oauth2/token?grant_type=client_credentials&scope=';

			$header = array(
				'Authorization: ' . ' Basic Ym90ckJRaUZzM2tvTTY1Wnc6YzE2ZTRhZTNjNmZiNGYxNDg5YWYxM2RlYmQ5MDJiNzg='
			);

			$context_options = array(
				'http' => array(
					'method' => 'POST',
					'header' => implode("\r\n", $header)
				)
			);

			$context = stream_context_create($context_options);

			$result = file_get_contents($url, false, $context);

			//echo $result;
			$jsonObj = json_decode($result);
//		foreach ($jsonObj as $key => $val) {
//			//echo $key;
//			echo $val;
//		}
			//echo print_r($jsonObj->data->access_token);
			//		echo gettype($jsonObj);
//		echo $jsonObj['data'];
			//echo $jsonObj->data;

			$access_token = $jsonObj->data->access_token;
			$this->writeLogFile("===access_token===");
			$this->writeLogFile($access_token);
			/*
            $url = 'https://storeapi.botim.me/storers/api/custom/order/add';

            $productInfo = ["originPrice"=> 5000,
                "finalPrice"=> 5000,
                "skuCurrency"=> "AED",
                "outProductId"=> "12509",
                "outSkuId"=> "12807",
                "skuCnt"=> 1];

    //echo $productInfo;



            $priceInfo =  [ "originPrice"=> 5000,
                "finalPrice"=> 5000,
                "discountPrice"=> 0,
                "displayCurrency"=>"AED",
                "exchangeRate"=>"1",
                "currency"=> "AED"];

    //echo $priceInfo;


            $orderDetail = array("orderDetail"=>array("priceInfo"=>$priceInfo,"productInfos"=>array($productInfo)),"uid"=>"NHVOMR0O","outOrderNo"=>"D170608828917703549","paymentMethod"=>"1");
            //echo json_encode($orderDetail);
    //exit(1);

            $postdata = http_build_query(json_encode($orderDetail));

            $header = array(
                'Authorization: ' . ' Bearer '.$access_token,
                 'accept:'.'*\/*',
                'content-type:'.'application/json'
            );

            $context_options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => implode("\r\n", $header),
                    'content' => $postdata
                )
            );

    // echo var_dump($context_options);

    // exit(1);


            $context = stream_context_create($context_options);

            $result = file_get_contents($url, false, $context);

            echo $result;*/

			require_once('vendor/autoload.php');

			$client = new \GuzzleHttp\Client();

			/*
                // 发起请求
                $url = "https://openauth-ae.botim.me/api/authserver/oauth2/token?grant_type=client_credentials&scope=";

                $response = $client->request('POST',$url,[
                        'headers' => [
                            'Authorization' => ' Basic Ym90ckJRaUZzM2tvTTY1Wnc6YzE2ZTRhZTNjNmZiNGYxNDg5YWYxM2RlYmQ5MDJiNzg=', // 设置认证信息
                        ],]

                );

                $jsonObj = $response->getBody();
        // echo gettype($jsonObj);
        // echo ($jsonObj);
        // echo "0000";
        // echo ($jsonObj->data);
        // echo "1111";
                $myarr = (json_decode($jsonObj,true));

        //echo ($myarr['data']['access_token']);
                $access_token =$myarr['data']['access_token'];*/


			$url = 'https://storeapi.botim.me/storers/api/custom/order/add';
			//$allMoney = 0.11;
			$productInfo = ["originPrice"=> 5000,
				"finalPrice"=> $allMoney*100,
				"skuCurrency"=> "AED",
				"outProductId"=> "12509",
				"outSkuId"=> "12807",
				"skuCnt"=> 1];
			//echo $productInfo;
			$priceInfo =  [ "originPrice"=> 5000,
				"finalPrice"=> $allMoney*100,
				"discountPrice"=> 0,
				"displayCurrency"=>"AED",
				"exchangeRate"=>"1",
				"currency"=> "AED"];
//
//			{
//				payPage: true,
//  payPageRedirectUrl: 'https://botim.me/cb/payby.cb'
//}
		   $paypaygeUrl = 'https://botim.me/cb/payby.cb';
			$payPageInfo = ["payPage"=> true,
				"payPageRedirectUrl"=> $paypaygeUrl];

			//echo $priceInfo;
			$orderDetail = array("orderDetail"=>array("priceInfo"=>$priceInfo,"productInfos"=>array($productInfo),"payPageInfo"=>$payPageInfo),"uid"=>"$userName","outOrderNo"=>"$order_no","paymentMethod"=>"1");
//		$header = array(
//			'Authorization: ' . ' Bearer '.$access_token,
//			'accept: ' .'*/*',
//			'content-type:'.'application/json'
//		);

			//echo json_encode($orderDetail);
			$response2 = $client->request('POST', 'https://storeapi.botim.me/storers/api/custom/order/add', [
				'body' => json_encode($orderDetail),
				'headers' => [
					'Accept' => '*/*',
					'Authorization' => ' Bearer '.$access_token,
					'Content-type' => 'application/json',
				],
			]);
//			echo json_encode($orderDetail);
//			exit(1);
			$this->writeLogFile("===order_no===");
			$this->writeLogFile($order_no);
			//$this->writeLogFile("===orderDetail===");
			//$this->writeLogFile($orderDetail);
//			echo json_encode($orderDetail);
//			exit(1);

			$jsonObj2 = $response2->getBody();
			//echo $jsonObj2;
			$myarr2 = (json_decode($jsonObj2,true));

			$this->writeLogFile("===transactionId===");
			$this->writeLogFile("===merchantOrderNo===");
			$this->writeLogFile($myarr2['data']['transactionId']);
			
			$this->writeLogFile($myarr2['data']);
			$myarr2['data']['order_no'] = $order_no;
			//$myarr2['data']['transactionId'];['transactionId']
			echo json_encode($myarr2['data']);
			//echo json_encode($myarr2);
//			require_once('../../../../vendor/autoload.php');
//			$client = new \GuzzleHttp\Client();
//			echo $client;
//			$response = $client->request('POST', 'https://storeapi.botim.me/storers/api/custom/order/add', [
//				'body' => '{"createTime":0,"uid":"string","outOrderNo":"string","referenceId":"string","orderDetail":{"productInfos":[{"spuId":0,"outProductId":"string","outSkuId":"string","skuCnt":0,"skuId":0,"finalPrice":0,"originPrice":0}],"payInfo":{"transactionId":"string","payMethod":"string","paidTime":0,"payStatus":"string","orderStatus":"string","sharingParam":{"amount":0,"currency":"string","sharingMemo":"string"}},"priceInfo":{"originPrice":0,"finalPrice":0,"otherPrice":[{"key":"string","rate":0,"type":0,"percentage":0}]},"orderAddressInfo":{"country":"string","city":"string","roomNo":"string","street":"string","type":"string","number":"string","firstName":"string","lastName":"string","latitude":"string","longitude":"string","state":"string","district":"string","bldg":"string","zip":"string","fat":"string","areaCode":"string","fullName":"string"},"payPageInfo":{"payPage":true,"payPageRedirectUrl":"string"},"currency":0,"paymentMethod":0,"payAndSign":true,"autoDebitInfo":{"autoDebit":true,"autoDebitProtocolNo":"string"}},"orderExt":{"pnr":"string"}}',
//				'headers' => [
//					'accept' => '*/*',
//					'authorization' => 'undefined',
//					'content-type' => 'application/json',
//				],
//			]);
//			echo json_encode($response);
			//print_r($or);
			//echo json_encode($or);


		} catch (\PayBy\Error\Base $e) {
			// 捕获报错信息
			//print_r($e);
			echo json_encode($e);
		}
	}
	public  function getOrder() {

		$goodsName=isset($_POST['goodsName']) ? $_POST['goodsName'] : "";
		$goodsId=isset($_POST['goodsId']) ? $_POST['goodsId'] : 0;
		$goodsNum=isset($_POST['goodsNum']) ? $_POST['goodsNum'] : 0;
		$allMoney=isset($_POST['allMoney']) ? $_POST['allMoney'] : "";
		$userId=isset($_POST['userId']) ? $_POST['userId'] : "";
		$userName=isset($_POST['ucenterid']) ? $_POST['ucenterid'] : "";
		$goodsInfo=isset($_POST['goodsInfo']) ? $_POST['goodsInfo'] : 0;
		$pay = System::load_app_class('pay','pay');
		$retVal = $pay->init($userId,1,'go_record');	//云购商品
//		if (!$ok) {
//			echo "pay init error!!!";
//			return;
//		}

		$Money = $allMoney;
		$dingdancode = '';

		list($result,$fanhuidingdan) = $pay->pay_bag($userId,$userName,$retVal[1]);
		if (!$result) {
			echo "result is error:".$result.$fanhuidingdan;
			return;
		}
		$dingdancode = $fanhuidingdan;

		// placeOrder
		//substr(md5(time()), 0, 20);
//		$dingdancode= pay_get_dingdan_code('D');		//订单号
		$order_no = $dingdancode;
		include_once dirname(__FILE__)."/PayBy/init.php";//引入文件需求
		$PARTNER_ID = '200000077725';

		\PayBy\PayBy::$caBundle=__DIR__ . '/PayBy/cert/cacert.pem';
		\PayBy\PayBy::setPartnerId($PARTNER_ID);
		$priKey = file_get_contents(__DIR__ . '/PayBy/cert/PayBy_key_private.pem');

		//\PayBy\PayBy::setApiKey($priKey);
		\PayBy\PayBy::setPrivateKey($priKey);

		\PayBy\PayBy::setApiBase('https://uat.test2pay.com/sgs/api');

		try {
			// bizContent
			$or = \PayBy\Api\Order::placeOrder(
				[
					"merchantOrderNo" => $order_no,
					"subject" => $goodsName,
					'totalAmount' => [
						'currency' => 'AED',
						'amount' => '0.1',
					],
					"paySceneCode" => "DYNQR",//"paySceneCode" => "DYNQR",
					"paySceneParams"=>[
						"redirectUrl"=>"http://152.136.235.238:84/#/draws",
					],
					"notifyUrl" => "http://152.136.235.238:84/yydb-server/?/mobile/mobile/payOk",
					"accessoryContent" => [
						'amountDetail' => [
							'vatAmount' => [
								'currency' => 'AED',
								'amount' => '0.1',
							],
						],
						'goodsDetail' => [
							'body' => 'Gifts',
							'goodsName' => $goodsName,
							'goodsId' => $goodsId,
						],
						'terminalDetail' => [
							'merchantName' => '200000077725',
						],
					],
					"reserved"=>$userId.'|'.$goodsInfo,
				]
			);
			//print_r($or);
			echo json_encode($or);
		} catch (\PayBy\Error\Base $e) {
			// 捕获报错信息
			//print_r($e);
			echo json_encode($e);
		}
	}

	public function payOk() {
		/*
		$plain = '{"notify_time":"20240105134000",
		"acquireOrder":{
		"product":"Basic Payment Gateway",
		"orderNo":"131704435140016056",
		"paySceneCode":"PAYPAGE",
		"subject":"Apple iPad Pro12.9-inch (6th generation) tablet 128GWLAN Deep Space Grey,Audi R8 2022 V10 Coupe performance,Ford Raptor,Apple Watch Ultra2 ",
		"accessoryContent":{
		"amountDetail":
		{"vatAmount":{"amount":0.10,"currency":"AED"}},
		"terminalDetail":{"merchantName":"EpicGadgets Hub"},
		"goodsDetail":
		{"goodsId":"15,18,21,23","body":"Gifts","goodsName":"Apple iPad Pro12.9-inch (6th generation) tablet 128GWLAN Deep Space Grey,Audi R8 2022 V10 Coupe performance,Ford Raptor,Apple Watch Ultra2 "}},
		"revoked":"false","merchantOrderNo":"0fd8c4989b65899d76bc","expiredTime":1704442340325,
		"requestTime":1704435140325,"totalAmount":{"amount":0.10,"currency":"AED"},
		"payeeMid":"200000077725","notifyUrl":"http://152.136.235.238:82/notify.php",
		"paymentInfo":{"cardInfo":{"last4":"0008","cardType":"DC","brand":"MASTERCARD"},
		"payChannel":"BANKCARD","paidTime":1704435207395,"payerFeeAmount":
		{"amount":0.00,"currency":"AED"},"paidAmount":{"amount":0.10,"currency":"AED"},
		"payerMid":"anonymousMember"},"status":"PAID_SUCCESS"},"_input_charset":"UTF-8",
		"notify_timestamp":1704447600021,"notify_id":"202401050013038981"}';
		$post_json = file_get_contents("php://input");
		//$jsonObj =json_decode($post_json) //第二个参数为false , json对象访问
		//echo $jsonObj->notify_id; // json_decode($post_json)
		$plain = $post_json;
		$jsonArr = json_decode($post_json,true); // 第二个参数为true,json数组
		//echo json_encode($jsonArr);

//		echo $jsonArr['acquireOrder']['totalAmount']['amount'];
//		exit(1);
//		$postData = $_POST;
//		echo count($postData);
		//$merchantOrderNo=isset($_POST['merchantOrderNo']) ? $_POST['merchantOrderNo'] : "";
		$merchantOrderNo=isset($jsonArr['acquireOrder']['merchantOrderNo']) ? $jsonArr['acquireOrder']['merchantOrderNo'] : "";
		$allMoney = isset($jsonArr['acquireOrder']['totalAmount']['amount']) ? $jsonArr['acquireOrder']['totalAmount']['amount'] : "";

		//$userId = 'abc';
		//$jsonArr['reserved'] = $userId.'|'.'25,1,26,1';
		//$userId = 2;
		//$jsonArr['reserved'] = $userId.'|'.'2,2';
		$reserved=isset($jsonArr['reserved']) ? $jsonArr['reserved'] : "";
		$reservedInfo = explode("|",$reserved);
		$userId = '';
		$goodsInfos = array();
		if(is_array($reservedInfo)) {
			$userId = (string)$reservedInfo[0];

			$goodsInfoArr = explode(",",$reservedInfo[1]);
			if(is_array($goodsInfoArr)) {
//				foreach ($goodsInfoArr as $key => $val) {
//					$goodsInfos[$key] = $val;
//				}
				for ($i = 1; $i <= count($goodsInfoArr); $i++) {
					if( $i % 2 == 0) {
						$goodsInfos[$goodsInfoArr[$i-2]] = $goodsInfoArr[$i-1];
					}
					//echo $array[$i] . " ";
				}
			}
		}

//		$userId=isset($_POST['userId']) ? $_POST['userId'] : "";
//		$goodsNum=isset($_POST['goodsNum']) ? $_POST['goodsNum'] : 0;
//
		$headers = getallheaders();
		//echo $headers['Content-Type'].'|'.$headers['Sign'];
		$pubKey = file_get_contents(__DIR__ . '/PayBy/cert/PayBy_key_public_key.pem');
		//echo $pubKey;
		$pubKeyRes = openssl_pkey_get_public($pubKey);
		$result = openssl_verify($plain, base64_decode($headers['Sign']), $pubKeyRes, OPENSSL_ALGO_SHA256);
		if ($result == 1) {
			//echo "signature is valid for given data.";
//			echo $result.'|'."SUCCESS";
			// 清理购物车

			// 发货? 已经给出去了
			// 更改数据库 状态
			$pay = System::load_app_class('pay','pay');
//			echo $userId;
//			echo $allMoney;
//			echo json_encode($goodsInfos);
//			echo $merchantOrderNo;
//			exit(1);
			list($result, $code) = $pay->payOk($userId,$allMoney,$goodsInfos,$merchantOrderNo);
	//		echo $result;
	//		echo $code;
	//		exit(1);
			$arr = array();
			array_push($arr,$result);
			array_push($arr,$code);
			$jsonObj = json_encode($arr);
			if($result) {
				return "SUCCESS";
			}
			echo $jsonObj;
			//echo $result.'|'.$code;
			// 提示购买成功
		} elseif ($result == 0) {
			echo "signature is invalid for given data.";
		} else {
			echo "error:".openssl_error_string();
		}
		openssl_free_key($pubKeyRes);
		return "ERROR UNKONWN";*/
	}

	public function getPayState() {
		$this->writeLogFile("xxxxxxxxxxgetPayState===");
		$dingdancode=safe_replace($this->segment(4));
		$userId=safe_replace($this->segment(5));
		$this->writeLogFile("dingdancode".$dingdancode);
		$this->writeLogFile("userId".$userId);
		$this->db = System::load_sys_class("model");
		$sql = "select status from `@#_member_go_record` where `code` = '$dingdancode'  and `uid` = '$userId'  limit 1";
        $this->writeLogFile("sql:".$sql);
		$zhifutype = $this->db->GetOne($sql);
		$this->writeLogFile("zhifutype:".$zhifutype);
		if(!empty($zhifutype)){
		    $pay_status = $zhifutype['status'];
		}
		$this->writeLogFile("pay_status:".$pay_status);
		//if(pay_status == )
		echo $pay_status;
		
		//$query_9 = $this->db->Query("UPDATE `@#_member_go_record` SET `status`='已付款,已发货,未完成' WHERE `code`='$dingdancode' and `uid` = '$uid'");

		//$go_record_info  = $this->db->GetOne($sql);
	}
	//购物车商品列表
	public function cartlist() {
		$webname=$this->_cfg['web_name'];
		$this->db = System::load_sys_class("model");

		$user=isset($_POST['uid']) ? $_POST['uid'] : "";
		$this->writeLogFile("===xxcartlist=user==".$user);
		$this->writeLogFile("===xxcartlist=user type==".gettype($user));
		//$this->writeLogFile($user);
		//$this->writeLogFile("===cartlist=user_end==");
		if($user == null || $user == "") {
			echo "uid is not null;";
			exit;
		}
		$cart_sql = "SELECT cart FROM `@#_cart` where `uid` = $user";
		$this->writeLogFile("===cart_sql===");
		$this->writeLogFile($cart_sql);
		$values = $this->db->GetList($cart_sql);
		$this->writeLogFile("===cartlist==values=");
		$this->writeLogFile($values);
		$this->writeLogFile("===cartlist==values type=");
		$this->writeLogFile(gettype($values));
		foreach ($values as $key => $val) {
			$this->writeLogFile("val['cart']:");
			$this->writeLogFile($val['cart']);
			$data = json_decode($val['cart'], true);
			//$this->writeLogFile('data type:');
			//$this->writeLogFile(gettype($data));
			$this->Cartlist = $data;
		}

		$this->writeLogFile("=final_Cartlist=");
		$this->writeLogFile($this->Cartlist);
		/*
23=>
num:5|
22=>
num:2|
21=>
num:1|*/
		$this->writeLogFile(gettype($this->Cartlist)); // array
		$this->writeLogFile("=is array??=");
//		$this->writeLogFile("666");
//		$Mcartlist=json_decode(stripslashes($this->Cartlist),true);
		//echo "<pre>";
		$Mcartlist = $this->Cartlist;

		//print_r($Mcartlist);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			//$this->writeLogFile("1shopids:".$shopids);
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
			//$this->writeLogFile("2shopids:".$shopids);
		} else {
			$this->writeLogFile("=is no array return=");
			$mycartArray = json_decode($this->Cartlist,true);
			$this->writeLogFile(gettype($mycartArray)); // array

			/*
			foreach($mycartArray as $key => $val){
				$shopids.=intval($key).',';
			}
			//$this->writeLogFile("1shopids:".$shopids);
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
			 */

		}
		//echo $shopids;
		$shoplist=array();
		if($shopids!=NULL){
			$shoparr=$this->db->GetList("SELECT * FROM `@#_shoplist` where `id` in($shopids)",array("key"=>"id"));
		}
		if(!empty($shoparr)){
			foreach($shoparr as $key=>$val){
				if($val['q_end_time']=='' || $val['q_end_time']==NULL){
			   $shoplist[$key]=$val;
			   $Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
			   $Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
			   $Mcartlist[$val['id']]['money']=$val['yunjiage']* $Mcartlist[$val['id']]['num'];

			}
		  }
			//$this->writeLogFile("========xxMcartlist===========");
			//$this->writeLogFile(json_encode($Mcartlist));
			//$this->writeLogFile("========xxMcartlist end===========");
			_setcookie('Cartlist',json_encode($Mcartlist),'');
		}

		$MoenyCount=0;
		$Cartshopinfo='{';
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
					$key=intval($key);
					if(isset($shoplist[$key])){
						$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
						$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
						$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
						$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
						$Cartshopinfo.="'$key':{'shenyu':".$shoplist[$key]['cart_shenyu'].",'num':".$val['num'].",'money':".$shoplist[$key]['yunjiage']."},";
					}
			}
		}

		$shop=0;

		if(!empty($shoplist)){
		   $shop=1;
		}
		//echo "<pre>";
		//print_r($Mcartlist);

        $MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		$Cartshopinfo.="'MoenyCount':$MoenyCount}";
		//include templates("mobile/cart","cartlist");
		$arr = array();
		array_push($arr,$shoplist);
		array_push($arr,$Cartshopinfo);
		array_push($arr,$Mcartlist);

		$jsonencode = json_encode($arr);
		//输出变量$jsonencode
		$this->writeLogFile($jsonencode);
		$this->writeLogFile("===Mcartlist_end===");
        echo $jsonencode;
	}


	//支付界面
	public function pay(){
        $webname=$this->_cfg['web_name'];
		parent::__construct();
		if(!$member=$this->userinfo){
		  header("location: ".WEB_PATH."/mobile/user/login");
		}
		$Mcartlist=json_decode(stripslashes($this->Cartlist),true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');

		}

		$shoplist=array();
		if($shopids!=NULL){
			$shoplist=$this->db->GetList("SELECT * FROM `@#_shoplist` where `id` in($shopids)",array("key"=>"id"));
		}
		$MoenyCount=0;
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
					$key=intval($key);
					if(isset($shoplist[$key])){
						$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
						$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
						$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
						$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];					
					}
			}
			$shopnum=0;  //表示有商品
		}else{
			_setcookie('Cartlist',NULL);
			//_message("购物车没有商品!",WEB_PATH);
			$shopnum=1; //表示没有商品
		}

		//总支付价格
		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		//会员余额
		$Money=$member['money'];
		//商品数量
		$shoplen=count($shoplist);

		$fufen = System::load_app_config("user_fufen",'','member');
		if($fufen['fufen_yuan']){
			$fufen_dikou = intval($member['score'] / $fufen['fufen_yuan']);
		}else{
			$fufen_dikou = 0;
		}
		$paylist = $this->db->GetList("select * from `@#_pay` where `pay_start` = '1'");

		session_start();
		$_SESSION['submitcode'] = $submitcode = uniqid();
		include templates("mobile/cart","payment");
	}

	//开始支付
	public function paysubmit(){
		$webname=$this->_cfg['web_name'];
		header("Cache-control: private");
		parent::__construct();
		if(!$this->userinfo){
		  header("location: ".WEB_PATH."/mobile/user/login");
		  exit;
		}

		session_start();


		 $checkpay=$this->segment(4);//获取支付方式  fufen   money  bank
		 $banktype=$this->segment(5);//获取选择的银行 CMBCHINA  ICBC CCB
		 $money=$this->segment(6);   //获取需支付金额
		 $fufen=$this->segment(7);   //获取福分
		 $submitcode1=$this->segment(8);   //获取SESSION

		 $uid = $this->userinfo['uid'];


		if(!empty($submitcode1)) {
			if(isset($_SESSION['submitcode'])){
				$submitcode2 = $_SESSION['submitcode'];
			}else{
				$submitcode2 = null;
			}
			if($submitcode1 == $submitcode2){
				unset($_SESSION["submitcode"]);
			}else{
				$WEB_PATH = WEB_PATH;
				_messagemobile("请不要重复提交...<a href='{$WEB_PATH}/mobile/cart/cartlist' style='color:#22c0ff'>返回购物车</a>查看");
				exit;
			}
		}else{
			$WEB_PATH = WEB_PATH;
			_messagemobile("正在返回购物车...<a href='{$WEB_PATH}/mobile/cart/cartlist' style='color:#22AAFF'>返回购物车</a>查看");
		}

//$zhifutype = $this->db->GetOne("select * from `@#_pay` where `pay_class` = '".$checkpay."' and `pay_start`='1' ");
		 //if(!$zhifutype){
		//	_messagemobile("手机支付只支持易宝,请联系站长开通！");
		// }
		 

		 $pay_checkbox=false;
		 $pay_type_bank=false;
		 $pay_type_id=false;

		 if($checkpay == 'money'){
			$pay_checkbox=true;
		 }

		 if($banktype != 'nobank'){
		   $pay_type_id=$banktype;
		 }

		 if(!empty($zhifutype)){
		    $pay_type_bank = $zhifutype['pay_class'];
		 }


		if(!$pay_type_id){
          if($checkpay != 'fufen' && $checkpay != 'money')
			_messagemobile("选择支付方式");
		}



		/*************
			start
		*************/


		$pay=System::load_app_class('pay','pay');
 //修改支付每次都要使用福分问题 lq 2014-12-01
        //$pay->fufen = $fufen;
		$pay->fufen = $checkpay=='fufen'?$fufen:0;
		$pay->pay_type_bank = $pay_type_bank;
		$ok = $pay->init($uid,$pay_type_id,'go_record');	//云购商品
		if($ok != 'ok'){
			_setcookie('Cartlist',NULL);
			_messagemobile("购物车没有商品请<a href='".WEB_PATH."/mobile/cart/cartlist' style='color:#22AAFF'>返回购物车</a>查看");
		}

		$check = $pay->go_pay($pay_checkbox);
		if(!$check){
			_messagemobile("订单添加失败,请<a href='".WEB_PATH."/mobile/cart/cartlist' style='color:#22AAFF'>返回购物车</a>查看");
		}
		if($check){
			//成功
			header("location: ".WEB_PATH."/mobile/cart/paysuccess");
		}else{
			//失败
			_setcookie('Cartlist',NULL);
			header("location: ".WEB_PATH."/mobile/mobile");
		}
		exit;
	}

	//成功页面
	public function paysuccess(){
	    $webname=$this->_cfg['web_name'];
		_setcookie('Cartlist',NULL);
		include templates("mobile/cart","paysuccess");
	}

	//充值
	public function addmoney(){
		parent::__construct();
		$webname=$this->_cfg['web_name'];
		 $money=$this->segment(4);//获取充值金额
		 $banktype=$this->segment(5);   //获取选择的银行 CMBCHINA  ICBC CCB

		if(!$this->userinfo){
		  header("location: ".WEB_PATH."/mobile/user/login");
		  exit;
		}

         $zhifutype = $this->db->GetOne("select * from `@#_pay` where `pay_class` = 'alipay'");
		 if(!$zhifutype){
			_messagemobile("手机支付只支持易宝,请联系站长开通！");
		 }

		 if(!empty($zhifutype)){
		    $pay_type_bank=$zhifutype['pay_class'];
		 }

		 $pay_type_id=$banktype;


		//$pay_type_bank=isset($_POST['pay_bank']) ? $_POST['pay_bank'] : false;
		//$pay_type_id=isset($_POST['account']) ? $_POST['account'] : false;
		//$money=intval($_POST['money']);
		$uid = $this->userinfo['uid'];
		$pay=System::load_app_class('pay','pay');
		$pay->pay_type_bank = $pay_type_bank;
		$pay->init($uid,$pay_type_id,'addmoney_record',$money);
	}

    public  function writeLogFile($array1) {
        //$path=date('Y-m-d-H-i-s').".log";
        $path=date('Y-m-d').".log";

		if(is_array($array1))
		{
			file_put_contents($path, count($array1)."\r\n", FILE_APPEND);


			foreach ($array1 as  $key=>$value)
			{
				file_put_contents($path, $key."=>\r\n", FILE_APPEND);
				//echo $value."<br/>";
				foreach ($value as $key1=>$value1)
				{
					file_put_contents($path, $key1.":".$value1."|", FILE_APPEND);
				}
				file_put_contents($path, "\r\n", FILE_APPEND);
			}
		}
		else
		{
			file_put_contents($path, $array1."\r\n", FILE_APPEND);
		}
    }
}


?>
